package com.hua.giftool.ui.screen

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.hua.giftool.R
import com.hua.giftool.ui.components.GifImage
import com.hua.giftool.utils.GifConstants
import com.hua.giftool.utils.convertVideoToGif
import com.hua.giftool.utils.createFFmpegCommand
import com.hua.giftool.utils.estimateGifFileSize
import com.hua.giftool.utils.getDurationFromUri
import com.hua.giftool.utils.stopFFmpegSession
import kotlinx.coroutines.launch

@Preview
@Composable
fun VideoToGifScreenPreview() {
    val activity = AppCompatActivity()
    activity.VideoToGifScreen()
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun <T : AppCompatActivity> T.VideoToGifScreen() {
    val context = LocalContext.current
    var selectedVideoUri by remember { mutableStateOf<Uri?>(null) }
    var conversionStatus by remember { mutableStateOf("") }
    val coroutineScope = rememberCoroutineScope()

    var targetFps by remember { mutableStateOf("${GifConstants.DEFAULT_FPS}") }
    var targetWidth by remember { mutableStateOf("${GifConstants.DEFAULT_WIDTH}") }
    var targetHeight by remember { mutableStateOf("${GifConstants.DEFAULT_HEIGHT}") }
    var estimatedFileSize by remember { mutableStateOf("") }
    var originalVideoDurationMs by remember { mutableStateOf<Long>(0) }

    var useCustomCommand by remember { mutableStateOf(false) }
    var customFFmpegCommand by remember { mutableStateOf("") }

    var isConverting by remember { mutableStateOf(false) }
    var conversionProgress by remember { mutableStateOf(0f) }

    val pickVideoLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        selectedVideoUri = uri
        conversionStatus = if (uri != null) context.getString(
            R.string.conversion_status_selected,
            uri.lastPathSegment
        ) else context.getString(R.string.conversion_status_no_selection)
        estimatedFileSize = ""
        if (uri != null) {
            originalVideoDurationMs = getDurationFromUri(uri)
            estimatedFileSize = estimateGifFileSize(
                uri,
                targetFps.toIntOrNull() ?: GifConstants.DEFAULT_FPS,
                targetWidth.toIntOrNull() ?: GifConstants.DEFAULT_WIDTH,
                targetHeight.toIntOrNull() ?: GifConstants.DEFAULT_HEIGHT,
                originalVideoDurationMs
            )
        }
        val inputVideoPathPlaceholder = "\"input_video_path\""
        val tempOutputGifPathPlaceholder = "\"output_gif_path\""
        customFFmpegCommand =
            "-i $inputVideoPathPlaceholder -vf \"fps=${targetFps.toIntOrNull() ?: GifConstants.DEFAULT_FPS},scale=${targetWidth.toIntOrNull() ?: GifConstants.DEFAULT_WIDTH}:${targetHeight.toIntOrNull() ?: GifConstants.DEFAULT_HEIGHT}:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=full[p];[s1][p]paletteuse=dither=sierra2_4a\" -loop 0 -y $tempOutputGifPathPlaceholder"
    }

    fun updateCommandAndSize() {
        val inputVideoPathPlaceholder = "\"input_video_path\""
        val tempOutputGifPathPlaceholder = "\"output_gif_path\""
        customFFmpegCommand = createFFmpegCommand(
            inputVideoPathPlaceholder,
            targetFps.toIntOrNull() ?: GifConstants.DEFAULT_FPS,
            targetWidth.toIntOrNull() ?: GifConstants.DEFAULT_WIDTH,
            targetHeight.toIntOrNull() ?: GifConstants.DEFAULT_HEIGHT,
            GifConstants.DEFAULT_LENS,
            tempOutputGifPathPlaceholder
        )
        estimatedFileSize = estimateGifFileSize(
            selectedVideoUri,
            targetFps.toIntOrNull() ?: GifConstants.DEFAULT_FPS,
            targetWidth.toIntOrNull() ?: GifConstants.DEFAULT_WIDTH,
            targetHeight.toIntOrNull() ?: GifConstants.DEFAULT_HEIGHT,
            originalVideoDurationMs
        )
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(rememberScrollState()), // Add vertical scroll
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        //选择视频按钮
        Button(onClick = {
            pickVideoLauncher.launch("video/*")
        }, enabled = !isConverting) {
            Text(stringResource(R.string.select_video_button))
        }
        //目标帧率
        OutlinedTextField(
            value = targetFps,
            onValueChange = { newValue ->
                targetFps = newValue
                updateCommandAndSize()
            },
            label = { Text(stringResource(R.string.target_fps_label)) },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            modifier = Modifier.fillMaxWidth(),
            enabled = !useCustomCommand && !isConverting
        )
        //目标宽度
        OutlinedTextField(
            value = targetWidth,
            onValueChange = { newValue ->
                targetWidth = newValue
                updateCommandAndSize()
            },
            label = { Text(stringResource(R.string.target_width_label)) },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            modifier = Modifier.fillMaxWidth(),
            enabled = !useCustomCommand && !isConverting
        )
        //目标高度
        OutlinedTextField(
            value = targetHeight,
            onValueChange = { newValue ->
                targetHeight = newValue
                updateCommandAndSize()
            },
            label = { Text(stringResource(R.string.target_height_label)) },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            modifier = Modifier.fillMaxWidth(),
            enabled = !useCustomCommand && !isConverting
        )

        // 自定义FFmpeg命令勾选框
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Checkbox(
                checked = useCustomCommand,
                onCheckedChange = { checked -> useCustomCommand = checked },
                enabled = !isConverting
            )
            Text(stringResource(R.string.use_custom_command_checkbox))
        }

        // 自定义FFmpeg命令输入框
        if (useCustomCommand) {
            OutlinedTextField(
                value = customFFmpegCommand,
                onValueChange = { customFFmpegCommand = it },
                label = { Text(stringResource(R.string.custom_ffmpeg_command_label)) },
                modifier = Modifier.fillMaxWidth(),
                enabled = !isConverting
            )
        }

        // 大小估算
        if (estimatedFileSize.isNotEmpty() && !useCustomCommand && !isConverting) {
            Text(text = stringResource(R.string.estimated_file_size_prefix, estimatedFileSize))
        }

        // 导出状态动图和进度条
        if (isConverting) {
            GifImage(
                gifResource = R.drawable.daomao,
                modifier = Modifier
                    .size(200.dp)
                    .align(Alignment.CenterHorizontally),
                contentDescription = R.string.conversion_status_converting
            )
            //进度条
            LinearProgressIndicator(
                progress = conversionProgress,
                modifier = Modifier.fillMaxWidth()
            )
            //进度百分比
            Text(
                text = "${(conversionProgress * 100).toInt()}%",
                modifier = Modifier.align(Alignment.CenterHorizontally)
            )
        }

        selectedVideoUri?.let { uri ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center
            ) {
                Button(onClick = {
                    stopFFmpegSession()
                    conversionProgress = 0f
                    isConverting = false
                }, enabled = isConverting) {
                    Text(stringResource(R.string.cancel_button))
                }
                Spacer(modifier = Modifier.width(20.dp))
                Button(onClick = {
                    isConverting = true
                    conversionStatus = context.getString(R.string.conversion_status_converting)
                    var fileSize = ""
                    coroutineScope.launch {
                        val success = convertVideoToGif(
                            uri,
                            targetFps.toIntOrNull() ?: GifConstants.DEFAULT_FPS,
                            targetWidth.toIntOrNull() ?: GifConstants.DEFAULT_WIDTH,
                            targetHeight.toIntOrNull() ?: GifConstants.DEFAULT_HEIGHT,
                            originalVideoDurationMs,
                            useCustomCommand,
                            customFFmpegCommand,
                            onProgress = { progress ->
                                conversionProgress = progress
                            },
                            onResultFileSize = {
                                fileSize = it
                            }
                        )
                        isConverting = false
                        conversionProgress = 0f
                        conversionStatus =
                            if (success)
                                context.getString(
                                    R.string.conversion_successful,
                                    fileSize,
                                    GifConstants.DEFAULT_OUTPUT_DIR
                                )
                            else context.getString(R.string.conversion_failed)
                    }
                }, enabled = !isConverting) {
                    Text(stringResource(R.string.convert_button))
                }
            }
            Text(text = conversionStatus)
        }
    }
}